package com.zretc.kscxmz.services.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zretc.kscxmz.entity.FileInfo;
import com.zretc.kscxmz.entity.Mail;
import com.zretc.kscxmz.entity.MailReceive;
import com.zretc.kscxmz.mappers.FileMapper;
import com.zretc.kscxmz.mappers.MailMapper;
import com.zretc.kscxmz.mappers.MailReceiveMapper;
import com.zretc.kscxmz.services.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MailServiceImpl implements MailService {
    Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
    @Autowired
    private MailMapper mapper;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private MailReceiveMapper mailReceiveMapper;
    @Override
    public PageInfo<Mail> getMailsByType(Map<String,String> map) {
        PageInfo<Mail> pageInfo = null;
        //开启分页
        PageHelper.startPage(Integer.parseInt(map.get("pageNum")),Integer.parseInt(map.get("pageSize")));
        //收件箱
        if ("收件箱".equals(map.get("type").trim())){
            //获取收件箱里面所有未删除的邮件
            List<Mail> mails = mapper.findReceiveMails(Integer.parseInt(map.get("userId")));
            pageInfo = new PageInfo<>(mails);
        }else if ("发件箱".equals(map.get("type").trim())){
            System.out.println("进入发件箱方法中");
            //获取该用户所有已提交且未删除的邮件
            List<Mail> mails = mapper.findSendMails(Integer.parseInt(map.get("userId")));
            pageInfo = new PageInfo<>(mails);
        }else if ("草稿箱".equals(map.get("type").trim())){
            //获取该用户所有未提交且未删除的邮件
            List<Mail> mails = mapper.findDraftMails(Integer.parseInt(map.get("userId")));
            pageInfo = new PageInfo<>(mails);
        }
        return pageInfo;
    }

    @Override
    public PageInfo<Mail> getMailsByConditions(Map<String,String> map) {
        PageInfo<Mail> pageInfo = null;
        //开启分页
        PageHelper.startPage(Integer.parseInt(map.get("pageNum")),Integer.parseInt(map.get("pageSize")));
        Map<String,String> conditionMap = new HashMap<>();//条件
        conditionMap.put("userId",map.get("userId"));

        String condition = map.get("condition").trim();//查询条件
        String searchContent = map.get("searchContent");//查询内容
        if ("全部".equals(condition)){
            conditionMap.put("type",null);
            conditionMap.put("title",null);
            conditionMap.put("status",null);
        }else if ("类型".equals(condition)){
            conditionMap.put("type",searchContent);
            conditionMap.put("title",null);
            conditionMap.put("status",null);
        }else if ("主题".equals(condition)){
            conditionMap.put("type",null);
            conditionMap.put("title","%"+searchContent+"%");
            conditionMap.put("status",null);
        }else{//状态
            conditionMap.put("type",null);
            conditionMap.put("title",null);
            conditionMap.put("status",searchContent);
        }
        //收件箱模糊搜索
        if ("收件箱".equals(map.get("type").trim())){
            List<Mail> receiveMails = mapper.findReceiveMailsByCondition(conditionMap);
            pageInfo = new PageInfo<>(receiveMails);
        }else if ("发件箱".equals(map.get("type").trim())){
            conditionMap.put("push","1");
            List<Mail> receiveMails = mapper.findSendAndDraftMailsByCondition(conditionMap);
            pageInfo = new PageInfo<>(receiveMails);
        }else if ("草稿箱".equals(map.get("type").trim())){
            conditionMap.put("push","0");
            List<Mail> receiveMails = mapper.findSendAndDraftMailsByCondition(conditionMap);
            pageInfo = new PageInfo<>(receiveMails);
        }
        return pageInfo;
    }

    @Override
    public int removeMails(Integer userId, String type, List<String> mailIdList) {
        String mailType = type.trim();
        int n = 0;
        if ("收件箱".equals(mailType)){
            n =  mapper.updateReceiveStatus(userId,mailIdList);
        }else if ("发件箱".equals(mailType) || "草稿箱".equals(mailType)){
            n = mapper.updateSendAndDraftStatus(userId,mailIdList);
        }
        return n;
    }

    @Override
    public Mail getMailsById(String mailId) {
        return mapper.findMailByMailId(Integer.parseInt(mailId));
    }

    @Override
    public int saveDraftMail(Mail mail,String mailId) {
        int n = 0;
        if ("".equals(mailId)){
            n = mapper.insertDraftMail(mail);
        }else{
            mail.setMailId(Integer.parseInt(mailId));
            n = mapper.updateDraftMail(mail);
        }
        return n;
    }

    @Override
    public int saveSendMail(Mail mail, FileInfo fileInfo,String mailId) {
        //判断mailId是否等于空穿，为空则是前端直接发送邮件得到的，不为空，则是前端通过草稿箱发送邮件得到的
        int n = 0;
        if (fileInfo != null){
            //1、查找文件表最后一个的id
            int lastFileId = fileMapper.findLastFileId();
            logger.info("=====lastMailId："+lastFileId);
            fileInfo.setFileId(lastFileId+1);
            mail.setMailFileId(lastFileId+1);
            //2.1、添加文件信息
            int f = fileMapper.insertFile(fileInfo);
        }
        if ("".equals(mailId)){//为空串则直接进行邮件信息插入
             //1、查找邮件表最后一个的id
            int lastMailId = mapper.findLastMailId();
            mail.setMailId(lastMailId+1);
            logger.info("=====lastMailId："+lastMailId);
            //2.2、添加已发送的邮件信息
            int m = mapper.insertSendMail(mail);

        }else{//不为空则修改草稿邮件的状态以及最终信息
            mail.setMailId(Integer.parseInt(mailId));
            logger.info("=====mailId："+mailId);
            int m = mapper.updateMailStatus(mail);
        }

        //2.3、添加接收表的信息，用于用户查看接收箱信息
        List<MailReceive> receiveList = new ArrayList<>();
        if (mail.getReceives().indexOf(",") != -1){//有多个接收者
            String[] receivers = mail.getReceives().split(",");
            for (String receiveMail:receivers) {//查找每个邮箱在用户表中所对应的用户（邮箱是唯一的）
                int userId = mailReceiveMapper.findReceiverIdByMailAccount(receiveMail);
                logger.info("接收者："+userId);
                MailReceive mailReceive = new MailReceive();
                mailReceive.setIsDel(0);
                mailReceive.setIsRead(0);
                mailReceive.setMailId(mail.getMailId());
                mailReceive.setMailReceiverId(userId);
                receiveList.add(mailReceive);
            }
        }else{//一个接收者
            int userId = mailReceiveMapper.findReceiverIdByMailAccount(mail.getReceives());
            logger.info("接收者："+userId);
            MailReceive mailReceive = new MailReceive();
            mailReceive.setIsDel(0);
            mailReceive.setIsRead(0);
            mailReceive.setMailId(mail.getMailId());
            mailReceive.setMailReceiverId(userId);
            receiveList.add(mailReceive);
        }
        //执行批量插入
        int r = mailReceiveMapper.insertReceive(receiveList);
        logger.info("是否批量插入成功："+r);

        return 1;
    }
}
